/*!
 * map
 * v 1.0.0
 * Copyright © 2015 - Blue Shark. All Rights Reserved  
 * by: 酱油鲜 (871839012@qq.com)
 * since: 2015‎年‎8月‎16‎日  
 * 
 */

require.config({
 	        paths: {echarts: 'dist/js'},
 	        packages: [{name: 'BMap',location: 'dist/js/BMap', main: 'main'}
 	                  
 	                 ]
});
function PersonAction(){
	var _searchContext='',BMapExt=null,map=null,myChart=null,interval_id,myCompOverlayList=[],self=this;
	var option = {
			tooltip:{trigger: 'item',formatter: '{b0}',},color:['#0af','#0af'],animationDurationUpdate:5000,//animation:false,
			series : [{name:"用户历史轨迹", type:'map', mapType: 'none',hoverable:false,data:[],geoCoord:{},
	                   markLine:{smooth:true,effect:{show:true,loop:false,scaleSize:1,period:30,color:'#fff',shadowBlur:0},
	                   itemStyle:{normal:{borderWidth:1,label:{show:false},lineStyle:{type:'solid',shadowBlur:10}}}, 
	                   data : []}}
	                 ]
     };
	function ComplexCustomOverlay(point, text, title,index){
    	this._point = point;
    	this._text = text;
    	this._title = title;
    	this._idseq=index;
    }
    ComplexCustomOverlay.prototype = new BMap.Overlay();
    ComplexCustomOverlay.prototype.initialize = function(map){
    	this._map = map;
    	var div =this._div = document.createElement("div");
    	//<button type="button" class="close" >×</button>
    	var $div=$(div);
    	$div.attr("id","pop-dialog_"+this._idseq);
    	$div.addClass("pop-dialog");
    	var button_obj=$("<button type='button' class='close' onclick=\"hideMenu('#pop-dialog_"+this._idseq+"')\""+"'>×</button>").appendTo($div);// 

    	var body_div =$("<div class='body'>").appendTo($div);//+this._text+
    	$("<div class='map_tip_head'>"+this._title+"<div>").appendTo(body_div);
    	$("<div class='map_tip_counten'>"+this._text+"<div>").appendTo(body_div);
    	
    	div=$div.get(0);
    	map.getPanes().labelPane.appendChild(div);
    	return div;
    }
    ComplexCustomOverlay.prototype.draw = function(){
    	var map = this._map;
    	var pixel = map.pointToOverlayPixel(this._point);
    	this._div.style.left = pixel.x+30 + "px";//+this._div.offsetWidth
    	this._div.style.top = pixel.y -this._div.offsetHeight/2+ "px";//+
    }
    ComplexCustomOverlay.prototype.addEventListener = function(event,fun){
    	this._div['on'+event] = fun;
    }
	self.search=function(name){
		console.log('开始搜索['+name+']');
		
		var submitUrl=temp();
		if(submitUrl){
			//self.destroy();//清空上次绘画 销毁图表
			if(interval_id!=null) clearInterval(interval_id);
			jQuery.get(submitUrl,null,function(jsonData){
				self.clear();//清空上次绘画 
				//console.log(jsonData);
				var geoCoord={};//坐标
	 			var make_info ={};//标注提示信息+坐标
	 			var line=[];//连线
				if(jsonData['code']=='0'){
					var data=jsonData.data;
					var tempLine=[];
 					var temppass="";
 					var tempdata_item=[];
 					var Begin_city;
 					for(var i=0,l=data.length;i<l;i++){
 						//console.log(data[i]);
 						if(geoCoord[data[i].reg_ip_geo['city']]==null){//没重复
 							if(jsonData.base_info[''+(parseInt(i)+1)].password!=null){//记录密码，如果某次密码为空，则可以取上次密码 1）其实可以不显示密码
 								temppass=jsonData.base_info[(parseInt(i)+1)+""].password;
 							}
 							if(i==0){//为第一个点加用户详细信息
 								var countent = [];
 								Begin_city=data[i].reg_ip_geo['city'];
 								if(jsonData.user_info[(parseInt(i)+1)+""].realname!=null)
 									countent.push("姓名："+jsonData.user_info[(parseInt(i)+1)+""].realname);
 								if(jsonData.user_info[(parseInt(i)+1)+""].phone!=null)
 									countent.push("手机："+jsonData.user_info[(parseInt(i)+1)+""].phone);
 								if(jsonData.user_info[(parseInt(i)+1)+""].email!=null)
 									countent.push("邮箱："+jsonData.user_info[(parseInt(i)+1)+""].email);
 								countent.push("密码："+temppass);
 								if(jsonData.user_info[(parseInt(i)+1)+""].qq!=null)
 									countent.push("QQ："+jsonData.user_info[(parseInt(i)+1)+""].qq);
 								if(jsonData.user_info[(parseInt(i)+1)+""].birthday!=null)
 									countent.push("生日："+new Date(parseInt(jsonData.user_info[(parseInt(i)+1)+""].birthday) * 1000).format("yyyy年MM月dd日"));
 								if(jsonData.user_info[(parseInt(i)+1)+""].political_status!=null)
 									countent.push("政治面貌："+jsonData.user_info[(parseInt(i)+1)+""].political_status);
 								if(jsonData.user_info[(parseInt(i)+1)+""].old_school!=null)
 									countent.push("学校："+jsonData.user_info[(parseInt(i)+1)+""].old_school);
 								if(jsonData.user_info[(parseInt(i)+1)+""].address!=null)
 									countent.push("住址："+jsonData.user_info[(parseInt(i)+1)+""].address);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][0]);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][1]);
 								tempdata_item.push(countent.join("<br>"));
 								tempdata_item.push(new Date(parseInt(data[i].reg_time) * 1000).format("yyyy年MM月"));
 								
 							} else{
 								var countent = [];
 								if(jsonData.base_info[(parseInt(i)+1)+""].user_name!=null)
 									countent.push("用户名："+jsonData.base_info[(parseInt(i)+1)+""].user_name);
 								if(jsonData.base_info[(parseInt(i)+1)+""].email!=null)
 									countent.push("邮箱："+jsonData.base_info[(parseInt(i)+1)+""].email);
 								countent.push("密码："+temppass);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][0]);
 								tempdata_item.push(data[i].reg_ip_geo['loc'][1]);
 								tempdata_item.push(countent.join("<br>"));
 								tempdata_item.push(new Date(parseInt(data[i].reg_time) * 1000).format("yyyy年MM月"));
 							}
 							make_info[data[i].reg_ip_geo['city']]=tempdata_item;
 		 					tempdata_item=[];
 							geoCoord[data[i].reg_ip_geo['city']]=data[i].reg_ip_geo['loc'];
 						}else{//重复的城市 替换 make_info 的值为新值
 							var repeatd_info=make_info[data[i].reg_ip_geo['city']];
 							console.log("重复城市名"+data[i].reg_ip_geo['city']+"序号："+i+repeatd_info[0]+","+repeatd_info[1]+","+repeatd_info[2]+",");
 							var tempcount=repeatd_info[2];
 							var temptitle=repeatd_info[3];
 							make_info[data[i].reg_ip_geo['city']][3]=new Date(parseInt(data[i].reg_time) * 1000).format("yyyy年MM月");
 							if(Begin_city==data[i].reg_ip_geo['city']){//如果是第一个点 则继续增加信息
								var countent = tempcount.split("<br>");
								countent.push("<span style='color: #ccc;'>"+temptitle+"</span>");//小标题
								if(jsonData.base_info[(parseInt(i)+1)+""].user_name!=null)
									countent.push("用户名："+jsonData.base_info[(parseInt(i)+1)+""].user_name);
								if(jsonData.base_info[(parseInt(i)+1)+""].email!=null)
									countent.push("邮箱："+jsonData.base_info[(parseInt(i)+1)+""].email);
								countent.push("密码："+jsonData.base_info[(parseInt(i)+1)+""].password);
								make_info[data[i].reg_ip_geo['city']][2]=countent.join("<br>");
 							}else{//后续历史点 则覆盖信息
 								var countent = [];
 								if(jsonData.base_info[(parseInt(i)+1)+""].user_name!=null)
 									countent.push("用户名："+jsonData.base_info[(parseInt(i)+1)+""].user_name);
 								if(jsonData.base_info[(parseInt(i)+1)+""].email!=null)
 									countent.push("邮箱："+jsonData.base_info[(parseInt(i)+1)+""].email);
 								countent.push("密码："+jsonData.base_info[(parseInt(i)+1)+""].password);
 								make_info[data[i].reg_ip_geo['city']][2]=countent.join("<br>");
 							}
 						}
 						if(tempLine.length==0){
 	 						tempLine.push({name:data[i].reg_ip_geo['city'],value:90});
	 					}else if(tempLine.length==1){
 							if(tempLine[0].name!=data[i].reg_ip_geo['city']){
 	 	 						tempLine.push({name:data[i].reg_ip_geo['city'],value:90});
 							}
	 					}
	 					if(tempLine.length==2) {
							line.push(tempLine);
							tempLine=[];
							tempLine.push({name:data[i].reg_ip_geo['city'],value:90});
	 					}
 					}
 					console.log(geoCoord);
 					console.log(make_info);
 					console.log(line);
 					addData(geoCoord,make_info,line);
				}
			},'json');
		}
	}
	function addData(geoCoord,make_info,line){
		//_init();//初始化图表
		option['series'][0]['geoCoord']=geoCoord;
		BMapExt.setOption(option);
		var tempCity=[]
		$.each(make_info,function(i,j,k){
			tempCity.push(i);
		});
		var _x= 0;
		function addMarker(x){
			var _obj=make_info[tempCity[x]];
			var point = new BMap.Point(_obj[0],_obj[1]);
		    map.centerAndZoom(point, 5);//将地图中心转移
		    
	        var myIcon = new BMap.Icon("dist/img/blue.png",  new BMap.Size(23, 23));
	        var marker = new BMap.Marker(point,{icon:myIcon});  // 创建标注
	    	map.addOverlay(marker);               // 将标注添加到地图中
	    	marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
	    	
	    	var myCompOverlay=new ComplexCustomOverlay(point, _obj[2], _obj[3],x); //这步是将覆盖物存到变量，以便下面使用。
	    	map.addOverlay(myCompOverlay);
	    	myCompOverlayList.push(marker);//放入数组 方便删除
	    	myCompOverlayList.push(myCompOverlay);//放入数组 方便删除
	    	
	    	addClickHandler(marker,x);
	    	return x++;
		}
		interval_id=setInterval(function(){
			if(_x==line.length){ 
				clearInterval(interval_id);
				if(0==line.length)
					addMarker(0);
				else
					option.series[0].markLine.data=line;
				BMapExt.setOption(option);
				window.setTimeout(closeAnimation, 2000);//延迟2秒后关闭动画效果
				return ;
			}
			option.series[0].markLine.data=[line[_x]];
			BMapExt.setOption(option);
			_x=addMarker(_x);
		},2000);
	}
   
 	function addClickHandler(marker,index){
		marker.addEventListener("click",function(e){ 
			var div_obj=$("#pop-dialog_"+index);
			div_obj.slideToggle();
			$("body").bind("mousedown",{id:"#pop-dialog_"+index}, onBodyDown);
		 }
		);
	}
	function closeAnimation(){
		option['animation']=false;
		BMapExt.setOption(option);
	}
	function openAnimation(){
		option['animation']=true;
		BMapExt.setOption(option);
	}
	function temp(){
		var submitURl="";
			//var data=$("#inp_search").closest('form').serializeArray();
			//暂时性辨别邮箱
			var out1="tang2007@163.com";
			var out2="pkpk3322@163.com";
			var out3="lalt_ralt@yahoo.com.cn";
			var emailtemp=$("#inp_search").val();
			if(out1.indexOf(emailtemp) >=0){
				submitURl="out.json";
			}else if(out2.indexOf(emailtemp) >=0){
				submitURl="out2.json";
			}else if(out3.indexOf(emailtemp) >= 0){
				submitURl="out3.json";
			}else{
				$.jGrowl({
	                header: "提示",
	                message: '没有结果'
	            });
				return false;
			}
		return submitURl;
	}
	self.clear=function(){
		//console.log($("div[id*='pop-dialog_']"));
		if(typeof myChart !=='undefined'){
			option.series[0].markLine.data=[];
			option['series'][0]['geoCoord']={};
			BMapExt.setOption(option,true);
			
			$.each(myCompOverlayList,function(i,j){
				map.removeOverlay(j);
			})
			openAnimation();
		}
	}
	
	function delloadAnimation(){
		//清除加载动画
		var parentD = $("#universal-preloader");
 		var pre = $("#universal-preloader>div");
 		pre.delay(500).animate({opacity:'0'},{duration:400, complete:function(){
 			parentD.animate({opacity:'0'},{duration:400, complete:function(){
 				parentD.remove();
 			    _searchContext = getQueryString('user_name');
 		 	    if(_searchContext != ''){
 					_searchContext = decodeURI(decodeURI(_searchContext));
 				    $("#inp_search").val(_searchContext);
 				   self.search(_searchContext);
 				}
 			}});
 		}});
	}
	/**
	 * 初始化
	 */
	function _init(){
 		require(['echarts','BMap', 'echarts/chart/map'], 
	    		function(echarts, BMapExtension){
 			$('#main').css({
	            height:$('body').height(),
	            width: $('body').width()
	        });
 			BMapExt = new BMapExtension($('#main')[0], BMap, echarts);
	        map = BMapExt.getMap();

	        var startPoint = {
	            x: 100.3467,
	            y: 41.4899
	        };
	        var point = new BMap.Point(startPoint.x, startPoint.y);
	        map.centerAndZoom(point, 5);
	        map.enableScrollWheelZoom(true);//启用滚轮放大
	        map.disableDoubleClickZoom(true);//禁止双击放大
	        map.setMapStyle({//样式固定 
	        	styleJson:[{"featureType":"land","elementType":"geometry","stylers":{"color":"#212121"}},{"featureType":"building","elementType":"geometry","stylers":{"color":"#2b2b2b"}},{"featureType":"highway","elementType":"all","stylers":{"color":"#313131","lightness":-42,"saturation":-91}},{"featureType":"arterial","elementType":"geometry","stylers":{"lightness":-77,"saturation":-94}},{"featureType":"green","elementType":"geometry","stylers":{"color":"#1b1b1b"}},{"featureType":"water","elementType":"geometry","stylers":{"color":"#181818"}},{"featureType":"subway","elementType":"geometry.stroke","stylers":{"color":"#181818"}},{"featureType":"railway","elementType":"geometry","stylers":{"lightness":-52}},{"featureType":"all","elementType":"labels.text.stroke","stylers":{"color":"#313131"}},{"featureType":"all","elementType":"labels.text.fill","stylers":{"color":"#8b8787"}},{"featureType":"manmade","elementType":"geometry","stylers":{"color":"#1b1b1b"}},{"featureType":"local","elementType":"geometry","stylers":{"lightness":-75,"saturation":-91}},{"featureType":"subway","elementType":"geometry","stylers":{"lightness":-65}},{"featureType":"railway","elementType":"all","stylers":{"color":"#252525","lightness":-40}},{"featureType":"boundary","elementType":"geometry","stylers":{"color":"#8b8787","weight":"1","lightness":-29}}]
	        });
	        var container = BMapExt.getEchartsContainer();
	        myChart = BMapExt.initECharts(container);
	        
	        BMapExt.setOption(option);
	        window.onresize = myChart.resize;
	        
 		});
	}
	/**
 	 * 获取url 参数
 	 */
 	function getQueryString(name) { 
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
		var r = window.location.search.substr(1).match(reg); 
		// location = encodeURI(encodeURI(url));
		if (r != null) return unescape(r[2]);; return ''; 
	}
 	delloadAnimation();
 	_init();
}
	/**
	 * 时间格式化
	 * @param format
	 * @returns
	 */
	Date.prototype.format = function(format){ 
		var o = { 
				"M+" : this.getMonth()+1, //month 
				"d+" : this.getDate(), //day 
				"h+" : this.getHours(), //hour 
				"m+" : this.getMinutes(), //minute 
				"s+" : this.getSeconds(), //second 
				"q+" : Math.floor((this.getMonth()+3)/3), //quarter 
				"S" : this.getMilliseconds() //millisecond 
			} 
			if(/(y+)/.test(format)) { 
				format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
			} 
			for(var k in o) { 
				if(new RegExp("("+ k +")").test(format)) { 
					format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
			} 
		} 
		return format;
	}
	
$(document).ready(function(){
	//console.log(document.getElementsByName('baiduAPI'));
	var scriptbaidu=document.getElementsByName('baiduAPI');

	var personAction= new PersonAction();
	$("#search_btn").click(function(){
		if($("#inp_search").val()==null||$("#inp_search").val()==""){
			$.jGrowl({
                header: "警告",
                message: '搜索内容不能为空'
            });
		}else{
			personAction['search']($("#inp_search").val());
			//personAction['destroy']();
		}
	});
//	
//	window.setTimeout(function() {
//	    console.log("Hello World!");
//	}, 5000);
//	window.setTimeout(function() {
//	    console.log("test");
//	}, 5000)
//	console.log('222');
})